const common = {
  // 解析css公式
  cssCalc: (calc) => {
    if (!calc) return 0;
    // 移除calc关键字并去除两侧空格
    calc = calc
      .replace(/calc\(/, "")
      .trim()
      .replace(/\)/, "")
      .trim();
    // 匹配加法和减法表达式
    let calculate = { firstNumber: 0, sign: "-", secondNumber: 0 };
    if (calc.indexOf("-") >= 0) {
      const charArray = calc.split("-");
      // 解析出第一个计算数字
      if (charArray[0]) {
        calculate.firstNumber =
          charArray[0].indexOf("vh") >= 0
            ? window.innerHeight
            : charArray[0].indexOf("vw") >= 0
            ? window.innerWidth
            : 0;
        if (charArray[0].indexOf("px") >= 0) {
          calculate.firstNumber = charArray[0].replace(/px/, "").trim();
        }
      }

      // 解析出第二个计算数字
      if (charArray[1]) {
        calculate.secondNumber = Number(charArray[1].replace(/px/, "").trim());
      }
    } else {
      return 0;
    }
    console.log(calculate);
    return eval(
      String(calculate.firstNumber)
        .concat(calculate.sign)
        .concat(String(calculate.secondNumber))
    );
  },

  // 随机字符串
  generateRandomNumberString(length) {
    let result = "";
    const characters = "0123456789";
    const charactersLength = characters.length;
    for (let i = 0; i < length; i++) {
      result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }
    return result;
  },

  // xml 转json
  xmlToJson(xmlString) {
    const parser = new DOMParser();
    const xmlDoc = parser.parseFromString(xmlString, "text/xml");
    const json = {};
    const parseElement = function (element) {
      if (element.hasChildNodes()) {
        for (let i = 0; i < element.childNodes.length; i++) {
          const child = element.childNodes[i];
          if (child.nodeType === 1) {
            if (child.hasChildNodes()) {
              json[child.nodeName] = parseElement(child);
            } else {
              json[child.nodeName] = child.textContent;
            }
          }
        }
      }
    };
    parseElement(xmlDoc.documentElement);
    return json;
  },

  formatChineseTime(seconds) {
    const timeUnits = [
      ["年", 365 * 24 * 60 * 60],
      ["个月", 30 * 24 * 60 * 60],
      ["天", 24 * 60 * 60],
      ["小时", 60 * 60],
      ["分钟", 60],
      ["秒", 1],
    ];

    let result = "";
    for (let i = 0; i < timeUnits.length; i++) {
      const [name, value] = timeUnits[i];
      const count = Math.floor(seconds / value);
      if (count > 0) {
        result += `${count}${name}`;
        seconds %= value;
      }
    }

    return result || "0秒";
  },
};

export default common;
